'use client';

import React from 'react';
import clsx from 'clsx';
import Link from 'next/link';
import { useSearchParams } from 'next/navigation';
import { objectClean } from 'src/utils';

export interface BreadcrumbProps {
  className?: string;
  items: Array<{
    label?: string;
    href?: string;
    title?: string;
    icon?: React.ReactNode;
  }>;
}

function BreadcrumbNoMemoized(props: BreadcrumbProps) {
  const { className, items } = props;

  const searchParams = useSearchParams();

  return (
    <nav className={clsx('breadcrumbs text-sm max-w-sm scrollbar-none', className)}>
      <ul>
        {items.map((item, index) => {
          const url = new URL(item.href || '', window.location.origin);
          const urlSearchParams = url.searchParams;
          const currentParams = Object.fromEntries(searchParams.entries());
          const targetParams = Object.fromEntries(urlSearchParams.entries());
          // 合并参数（targetParams 优先级高于 currentParams）
          const mergedParams = objectClean({ ...currentParams, ...targetParams }, ['empty']);
          // 生成新的查询字符串
          const mergedQuery = new URLSearchParams(mergedParams).toString();
          return (
            <li key={index}>
              {item.href && index !== items.length - 1 ? (
                <Link href={`${url.pathname}?${mergedQuery}`} title={item.title || item.label}>
                  {item.icon}
                  {item.label}
                </Link>
              ) : (
                <span className="text-gray-500 dark:text-gray-400 hover:cursor-[unset] hover:no-underline!">
                  {item.icon}
                  {item.label}
                </span>
              )}
            </li>
          );
        })}
      </ul>
    </nav>
  );
}

export const Breadcrumb = React.memo(BreadcrumbNoMemoized);
